import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authService } from '../services/auth'
import router from '../router'

export const useUserStore = defineStore('user', () => {
  const user = ref(null)
  const token = ref(localStorage.getItem('token') || null)
  
  const isLoggedIn = computed(() => {
    const tokenValue = token.value
    console.log('检查登录状态 - token:', tokenValue)
    return !!tokenValue
  })
  
  async function login(credentials) {
    try {
      console.log('开始登录请求，凭据:', credentials)
      const response = await authService.login(credentials)
      console.log('登录响应:', response)
      
      if (response && response.code === 0 && response.data && response.data.access_token) {
        console.log('登录成功，设置token:', response.data.access_token)
        token.value = response.data.access_token
        user.value = response.data.user
        localStorage.setItem('token', response.data.access_token)
        console.log('token设置完成，当前值:', token.value)
        console.log('localStorage中的token:', localStorage.getItem('token'))
        return true
      } else {
        console.error('登录响应格式不正确:', response)
        return false
      }
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }
  
  async function register(userData) {
    try {
      const response = await authService.register(userData)
      // 注册成功后，需要登录获取token
      if (response && response.data) {
        // 使用注册的用户名和密码登录
        const loginResult = await login({
          username: userData.username,
          password: userData.password
        })
        return loginResult
      }
      return false
    } catch (error) {
      console.error('注册失败:', error)
      return false
    }
  }
  
  async function logout() {
    token.value = null
    user.value = null
    localStorage.removeItem('token')
    router.push('/auth/login')
  }
  
  async function fetchUserProfile() {
    if (token.value) {
      try {
        const response = await authService.getProfile()
        if (response && response.data) {
          user.value = response.data
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        logout()
      }
    }
  }
  
  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    fetchUserProfile
  }
})